using System;
using System.Diagnostics;
using System.Reflection;
using System.Web;

namespace Impact.Web.Foundation
{
    /// <summary>
    /// Utility class for web-related functions
    /// </summary>
    public class WebUtility
    {

        /// <summary>
        /// Gets the version of the executing assembly
        /// </summary>
        public static string Version
        {
            get
            {
                return string.Format( "v{0}", Assembly.GetAssembly( typeof(WebUtility) ).GetName().Version );
            }
        }

        /// <summary>
        /// Gets the uptime of the server
        /// </summary>
        public static string UpTime
        {
            get
            {
                PerformanceCounter pcUptime = new PerformanceCounter( "System", "System Up Time", true );
                // MSDN notes the following:
                // "If the calculated value of a counter depends on two counter reads, the
                // first read returns 0.0."
                //
                // It appears that System Up Time is one of those counters, hence the two
                // consecutive calls to NextValue ().
                pcUptime.NextValue();

                double dUptime = Convert.ToDouble( pcUptime.NextValue() );
                long ticks = Convert.ToInt64( dUptime * 10000000.0 );
                TimeSpan ts = new TimeSpan( ticks );

                return string.Format( "Server has been up for: {0} days, {1} hours, {2} minutes.", ts.Days, ts.Hours, ts.Minutes );
            }
        }

        /// <summary>
        /// Gets the absolute root of the website.
        /// </summary>
        /// <value>A string that ends with a '/'.</value>
        public static Uri ToAbsolute( string path )
        {
            HttpContext context = HttpContext.Current;
            if ( context == null )
                throw new Exception( "The current HttpContext is null" );

            return new Uri( string.Format( "{0}://{1}{2}", context.Request.Url.Scheme,
                context.Request.Url.Authority, VirtualPathUtility.ToAbsolute( path ) ) );
        }


    }
}
